package com.yfree.utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.widget.RemoteViews;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.yfree.R;
import com.yfree.YConfig;
import com.yfree.activities.YActivity;
import com.yfree.activities.YActivityManager;
import com.yfree.models.YVersionModel;
import com.yfree.listeners.OnCheckedListener;
import com.yfree.listeners.YAjaxCallBack;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import java.io.File;
import java.util.ArrayList;

public class YUpdateUtils {
    public static void checkUpdate(final YActivity context) {
        checkUpdate(context, new OnCheckedListener() {
            @Override
            public void onIsNewest(YVersionModel yVersionModel) {
                context.yToast("已为最新版本");
            }

            @Override
            public void onFail() {
            }
        }, true, true, true);
    }

    public static void checkUpdate(final YActivity context, final OnCheckedListener onCheckedListener, final boolean mustUpdate, final boolean showProgress, boolean showErrorToast) {
        if (TextUtils.isEmpty(YConfig.UPDATEIP) || TextUtils.isEmpty(YConfig.checkUpdateInterface))
            context.yLog("版本校验工具参数不完整，请配置YConfig");
        else
            context.yPost(YConfig.UPDATEIP, YConfig.checkUpdateInterface, null, new YAjaxCallBack<YVersionModel>(context, showErrorToast) {
                @Override
                public void onSuccessed(@NonNull ArrayList<YVersionModel> results) {
                    try {
                        final YVersionModel yVersionModel = results.get(0);
                        final String newVersion = yVersionModel.getAndroid_version();
                        if (Integer.parseInt(newVersion) != YVersionUtils.getVersionCode(context.context))
                            if (mustUpdate)
                                update(context, newVersion, yVersionModel.getAndroid_url());
                            else
                                context.yShowBuilder("检测到新版本", "升级", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        update(context, newVersion, yVersionModel.getAndroid_url());
                                    }
                                }, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        onCheckedListener.onIsNewest(yVersionModel);
                                    }
                                }, false);
                        else
                            onCheckedListener.onIsNewest(yVersionModel);
                    } catch (Exception e) {
                        onCheckedListener.onFail();
                    }
                }

                @Override
                public void onFail(Object response, Throwable throwable, String errorNo, String strMsg) {
                    super.onFail(response, throwable, errorNo, strMsg);
                    onCheckedListener.onFail();
                }
            }, showProgress);
    }

    public static void update(final YActivity context, final String newVersion, final String url) {
        final ProgressDialog progressDialog = new ProgressDialog(context.context);
        progressDialog.setTitle(YAppUtils.getAppName(context) + "提示");
        progressDialog.setIcon(YConfig.logo_icon);
        progressDialog.setMessage("正在获取最新版本");
        progressDialog.setMax(100);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
        final RemoteViews remoteViews = new RemoteViews(context.context.getPackageName(), R.layout.notification_update_version);
        remoteViews.setImageViewResource(R.id.image, YConfig.logo_icon);
        final Notification notification = new Notification();
        notification.icon = YConfig.logo_icon;
        notification.contentView = remoteViews;
        // notification.flags |= Notification.FLAG_NO_CLEAR;
        // 兼容Flutter
        if (context.yNotificationManager == null)
            context.yNotificationManager = (NotificationManager) context.context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (context.yBasePath == null) {
//            context.yBasePath = Environment.getExternalStorageDirectory().getAbsolutePath() + YConfig.PROJECTBASEDIR;
            context.yBasePath = context.getExternalFilesDir(YConfig.YFreeDir).getAbsolutePath() + YConfig.PROJECTBASEDIR;
            File readyFile = new File(context.yBasePath);
            if (!readyFile.exists())
                if (!readyFile.mkdirs()) {
                    context.yShowBuilder("初始化app目录失败，请检查存储空间！", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            YActivityManager.finishApplication();
                        }
                    }, null, false);
                    return;
                }
        }
        String updateDir = context.yBasePath + YConfig.updateDir + "/";
        File file = new File(updateDir);
        if (!file.exists())
            if (!file.mkdirs()) {
                context.yNotificationManager.cancel(0);
                progressDialog.dismiss();
                showErrorBuilder(context, newVersion, url, "下载目录初始化失败");
                return;
            }
        new FinalHttp().download(url, updateDir + newVersion + ".apk", new AjaxCallBack<File>() {
            public void onStart() {
                context.yNotificationManager.notify(0, notification);
            }

            public void onLoading(long count, long current) {
                remoteViews.setProgressBar(R.id.pb, (int) count, (int) current, false);
                float download = 0;
                if (count != 0) {
                    download = (current / (float) count) * 100;
                }
                remoteViews.setTextViewText(R.id.tv, "已下载" + download + "%");
                context.yNotificationManager.notify(0, notification);
                progressDialog.setProgress((int) download);
            }

            public void onSuccess(final File t) {
                context.yNotificationManager.cancel(0);
                progressDialog.dismiss();
                StringBuilder sb = new StringBuilder();
                sb.append("application");
                sb.append("/");
                sb.append("vnd");
                sb.append(".");
                sb.append("android");
                sb.append(".");
                sb.append("package");
                sb.append("-");
                sb.append("archive");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    try {
                        try {
                            String[] args = {"chmod", "777", t.getAbsolutePath()};
                            Runtime.getRuntime().exec(args);
                        } catch (Exception ignored) {
                        }
                        context.context.startActivity(
                                new Intent(Intent.ACTION_VIEW)
                                        .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                        .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                                        .setDataAndType(FileProvider.getUriForFile(context.context, context.context.getPackageName() + ".YFileProvider", t), sb.toString())
                        );
                        YActivityManager.finishApplication();
                    } catch (Exception ignored) {
                        context.yShowBuilder("唤起系统安装器失败，是否重试？", "重试", "返回", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                onSuccess(t);
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (YActivityManager.getActivities().size() <= 1)
                                    context.context.finish();
                            }
                        }, false);
                    }
                } else {
                    context.context.startActivity(
                            new Intent(Intent.ACTION_VIEW)
                                    .setDataAndType(Uri.fromFile(t), sb.toString())
                    );
                    YActivityManager.finishApplication();
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                context.yNotificationManager.cancel(0);
                progressDialog.dismiss();
                showErrorBuilder(context, newVersion, url, "下载失败");
            }
        });
    }

    private static void showErrorBuilder(final YActivity context, final String newVersion, final String url, String message) {
        context.yShowBuilder(message, "重试", "返回", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                update(context, newVersion, url);
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (YActivityManager.getActivities().size() <= 1)
                    context.context.finish();
            }
        }, false);
    }
//
//    //安装应用的流程
//    private void installProcess(YActivity context, File apk) {
//        boolean haveInstallPermission;
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            //先获取是否有安装未知来源应用的权限
//            haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
//            if (!haveInstallPermission) {//没有权限
//                context.yShowBuilder("安装应用需要打开未知来源权限，请去设置中开启权限", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                            startInstallPermissionSettingActivity();
//                        }
//                    }
//                }, null, false);
//                return;
//            }
//        }
//        //有权限，开始安装应用程序
//        installApk(apk);
//    }
//
//
//    @RequiresApi(api = Build.VERSION_CODES.O)
//    private void startInstallPermissionSettingActivity(YActivity context) {
//        Uri packageURI = Uri.parse("package:" + context.getPackageName());
//        //注意这个是8.0新API
//        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
//        context.startActivityForResult(intent, 10086);
//    }
//
//    //安装应用
//    private void installApk(YActivity context, File apk) {
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
//            intent.setDataAndType(Uri.fromFile(apk), "application/vnd.android.package-archive");
//        } else {//Android7.0之后获取uri要用contentProvider
//            Uri uri = AppCommonUtils.getUriFromFile(context.getBaseContext(), apk);
//            intent.setDataAndType(uri, "application/vnd.android.package-archive");
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        }
//
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.getBaseContext().startActivity(intent);
//    }
}
